/*
 *
 * This is a VoIP Application designed for local-network usage for voice and
 * messaging
 * Copyright (C) 2012  Imran M Yousuf (imyousuf@smitsol.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.smitsol.voip.api.impl;

import com.smitsol.voip.api.Binding;
import com.smitsol.voip.api.BindingService;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 * @author imyousuf
 */
class BindingServiceImpl implements BindingService {

  private final ConcurrentHashMap<String, List<Binding>> bindings = new ConcurrentHashMap<String, List<Binding>>();

  public void addBinding(Binding binding) {
    bindings.putIfAbsent(binding.getAddressOfRecord(), new ArrayList<Binding>());
    List<Binding> aorBindings = bindings.get(binding.getAddressOfRecord());
    removeBinding(binding);
    aorBindings.add(binding);
  }

  public List<Binding> getBindings(String aor) {
    List<Binding> aorBindings = bindings.get(aor);
    return aorBindings == null ? Collections.<Binding>emptyList() : Collections.<Binding>unmodifiableList(aorBindings);
  }

  public boolean removeBinding(Binding binding) {
    Binding fBinding = findBinding(binding);
    List<Binding> aorBindings = bindings.get(binding.getAddressOfRecord());
    if (aorBindings != null && fBinding != null) {
      aorBindings.remove(fBinding);
      return true;
    }
    else {
      return false;
    }
  }

  protected Binding findBinding(Binding qBinding) {
    for (Binding binding : getBindings(qBinding.getAddressOfRecord())) {
      if (binding.getAddressOfRecord().equals(qBinding.getAddressOfRecord()) && binding.getContactUri().equals(qBinding.
          getContactUri())) {
        return binding;
      }
    }
    return null;
  }
}
